﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Nova_Common;
using Nova_MOD;
using Nova_BLL;
using Nova_DAL;
using System.Data.SqlClient;
using System.Data.Common;

public partial class Move_CargoMove : System.Web.UI.Page
{
    string lbl_LaneNo = ""; //巷道号
    string cid = "";        ////层
    int rid = 0;        //gridview行的编号
    int iLcol = 0;
    string PosID = "";

    //20210429 NF项目双伸位巷道集合  需要结合项目双伸位巷道修改
    string[] ExtensionLanelists = new string[] { "1" };

    DataSet ds = null;
    DataTable myTable = null;
    int iLineNo = 0;               //排
    int iLayNo = 0;           //层
    const int colStart = 60;
    DbHelper access = new DbHelper();

    DbCommand cmd = null;

    //新加
    int Li = 0;
    int Co = 0;
    int La = 0;
    int i = 0;
    int j = 0;
    int k = 0;





    Nova_Common.LoginLogic cLoginLogic = new LoginLogic();
    Nova_BLL.TBase_Position Nova_BLL_TBase_Position = new Nova_BLL.TBase_Position();
    Nova_BLL.TLaneDefine Nova_BLL_TLaneDefine = new Nova_BLL.TLaneDefine();
    Nova_BLL.TPosState Nova_BLL_TPostState = new Nova_BLL.TPosState();
    Nova_MOD.TBase_Position Nova_MOD_TBase_Position = new Nova_MOD.TBase_Position();
    Nova_BLL.Users Nova_BLL_Users = new Nova_BLL.Users();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Nova_Common.LoginLogic.IsLogin();
            ddlbind();
            //dlistPosbind();
            gvbind();

        }
    }


    /// <summary>
    /// 加载巷道号下拉选择框  除去动态尺寸巷道3#  
    /// #3巷道移库功能禁止
    /// </summary>
    protected void ddlbind()
    {
        ds = Nova_BLL_TLaneDefine.DataSetTLaneDefineNoDynamicsSizeLane();
        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        {
            ddlNo_Lane.DataSource = ds;
            ddlNo_Lane.DataValueField = "No_Lane";
            ddlNo_Lane.DataTextField = "No_Lane_Text";
            ddlNo_Lane.DataBind();
        }

    }

    protected bool reInt(string strNum)
    {
        try
        {
            int var1 = Convert.ToInt32(strNum);
            return true;
        }
        catch
        {
            return false;
        }
    }


    protected void gvbind()
    {
        int subArea = int.Parse(ddlNo_Col.SelectedValue);
        lbl_LaneNo = ddlNo_Lane.SelectedValue.ToString();
        //myTable = Nova_BLL_TBase_Position.DTableTBase_PositionZoneID(lbl_ZoneID, lbl_LaneNo);
        myTable = Nova_BLL_TBase_Position.DTableTBase_PositionZoneIDPosImg("10", lbl_LaneNo, subArea);
        if (myTable != null && myTable.Rows.Count > 0)
        {
            GV.DataSource = myTable;
            GV.DataBind();
        }
        //设置按钮的显示
        SetForm();

        //没有物料的查询条件，则不执行货位显示特定颜色
         if (string.IsNullOrEmpty(txtMat_Code.Text.Trim()) && string.IsNullOrEmpty(txtMat_Name.Text.Trim()))
         {
            return;
         }

       //查询条件匹配的，货位显示特定颜色
        DataTable dt = this.findPos();
        if (dt.Rows.Count > 0)
        {
            int x = 0;
            int y = 0;
            int line = 0;
            int lane = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                lane = int.Parse(dt.Rows[i][1].ToString());  //巷道
                line = int.Parse(dt.Rows[i][2].ToString());  //排
                x = int.Parse(dt.Rows[i][4].ToString());  //层
                y = int.Parse(dt.Rows[i][3].ToString());      //列

                if (line == 2)   
                {
                    if (!ExtensionLanelists.Contains(lane.ToString()))    //双伸位巷道处理
                    { x = x + 6; }    //双伸位最大层数为6层，其他项目根据实际情况修改。
                    else
                    { x = x + 4; }     //单伸位最大层数为3层，其他项目根据实际情况修改。
                }
                GV.Rows[x-1].Cells[y+1].BackColor = System.Drawing.Color.FromName("#6699FF");
                //GV.Rows[x - 1].Cells[y].BackColor = System.Drawing.Color.FromName("#6699FF");
            }
        }
        dt.Dispose();

        
    }

    /// <summary>
    /// 设置窗体  
    /// </summary>
    private void SetForm()
    {
        if (!ExtensionLanelists.Contains(ddlNo_Lane.SelectedValue.ToString()))   //双伸位 终点货位设定按钮 隐藏  算法展示显示自动获取终点位置
        {
            this.btnEnd.Visible = false;
            this.rdbSuanFa.SelectedItem.Text = "自动获取终点位置";
            
        }
        else
        {
            //this.btnEnd.Visible = true;
            this.rdbSuanFa.SelectedItem.Text = "点点移动"; //单伸位巷道    终点货位设定按钮 算法展示显示点点移动

        }
    }

    private void SetGridColor(GridView GV, Int32 X, Int32 Y, String ColorValue)
    {
        GV.BackColor = System.Drawing.Color.FromName("#ffffff");
        GV.Rows[X].Cells[Y].BackColor = System.Drawing.Color.FromName(ColorValue);

    }

    protected void ddlNo_Lane_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvbind();
    }



    protected void GV_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        #region 老的卡
        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    e.Row.Cells[1].Attributes["style"] = "width:40px;";
        //    cid = e.Row.Cells[1].Text.ToString().Substring(0, 1);
        //    rid = e.Row.RowIndex + 1;
        //    lbl_LaneNo = ddlNo_Lane.SelectedValue.ToString();       //巷道号
        //    iLineNo = Convert.ToInt32(e.Row.Cells[0].Text.Substring(0, 1));     //排
        //    //iLcol = e.Row.RowIndex;         //列
        //    iLayNo = Convert.ToInt32(e.Row.Cells[1].Text.Substring(0, e.Row.Cells[1].Text.Length - 1));     //层

        //    DataRowView dv = (DataRowView)e.Row.DataItem;
        //    for (int i = 0; i < e.Row.Cells.Count; i++)
        //    {


        //        if (i == 0)
        //        {
        //            iLcol = 1;
        //        }
        //        else if (i == 1)
        //        {
        //            iLcol = 2;
        //        }
        //        else
        //        {

        //            iLcol = i;
        //        }
        //        if (i > 1)
        //        {
        //            if (e.Row.Cells[i].Text.ToString() == "1")
        //            {
        //                PosID = "10" + lbl_LaneNo.PadLeft(2, '0') + iLineNo.ToString() + iLcol.ToString().PadLeft(3, '0') + iLayNo.ToString().PadLeft(2, '0') + "00";
        //            }
        //            e.Row.Cells[i].Text = Nova_BLL_TPostState.strPosImg(e.Row.Cells[i].Text.ToString());

        //        }
        //        e.Row.Cells[i].Attributes["onclick"] = "showEdit(" + lbl_LaneNo + "," + e.Row.Cells[0].Text.ToString().Substring(0, 1) + "," + iLcol + "," + cid + "," + rid + ");";
        //        e.Row.Cells[i].Attributes["style"] = "Cursor:hand";
        //        //e.Row.Cells[i].Attributes.Add("OnMouseOut", "this.style.backgroundColor='#ffffff';");
        //        //e.Row.Cells[i].Attributes.Add("OnMouseOver", "this.style.backgroundColor='#6699FF';");

        //    }
        //}
        #endregion

        //每行绑定  点击行行触发SelectedIndexChanging事件（SelectedIndexChanging 不能自动触发）
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["style"] = "cursor:hand";

            #region   //点击行触发SelectedIndexChanging事件
            PostBackOptions myPostBackOptions = new PostBackOptions(this);
            myPostBackOptions.AutoPostBack = false;
            myPostBackOptions.PerformValidation = false;
            myPostBackOptions.RequiresJavaScriptProtocol = true; //加入javascript:头
            String evt = Page.ClientScript.GetPostBackClientHyperlink(sender as GridView, "Select$" + e.Row.RowIndex.ToString());
            e.Row.Attributes.Add("onclick", evt);
            #endregion
        }

    }


    //索引变更事件--为选择的索引行的所有单元格 绑定单击功能（文本框显示单元格的行、列）
    protected void GV_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        this.GV.SelectedIndex = e.NewSelectedIndex;
        int index = e.NewSelectedIndex;
        string rid = (index + 1).ToString(); //行号
        //GV.Rows[index].BackColor = System.Drawing.Color.FromName("#CCCCCC"); //选中的行显示灰色

        lbl_LaneNo = ddlNo_Lane.SelectedValue.ToString();       //巷道号
        iLineNo = Convert.ToInt32(this.GV.Rows[index].Cells[0].Text.Substring(0, 1));     //排
        //iLcol = e.Row.RowIndex;         //列
        iLayNo = Convert.ToInt32(this.GV.Rows[index].Cells[1].Text.Substring(0, this.GV.Rows[index].Cells[1].Text.Length - 1));     //层



        for (int i = 0; i < this.GV.Rows[index].Cells.Count; i++)
        {

            //列的数据获取处理 列号从1开始
            if (i < 2)
            {
                iLcol = 1;
            }
            else
            {
                iLcol = i - 1;
            }
            iLcol = ddlNo_Col.SelectedValue == "1" ? iLcol : (colStart + iLcol);

            //列的数据获取处理  列号从2开始
            //if (i < 2)
            //{
            //    iLcol = 2;
            //}
            //else
            //{
            //    iLcol = i;
            //}

            this.GV.Rows[index].Cells[i].Attributes["onclick"] = "showEdit(" + lbl_LaneNo + "," + iLineNo + "," + iLcol + "," + iLayNo + "," + rid + ");";


        }



    }



    //查找满足条件的货位
    private DataTable findPos()
    {
        DataTable dt = new DataTable();
        DataSet ds = new DataSet();
        String sql = @"Select Distinct TBP.Pos_ID,TBP.No_Lane,TBP.No_Line,TBP.No_Col,TBP.No_Layer
                        from TBase_Position TBP
                        Left Outer Join TRelations TRP on TBP.Pos_ID=TRP.Pos_ID
                        Left Outer Join TBase_TrayPos TBT on TRP.Tray_ID=TBT.Tray_ID
                        Left Outer Join TRel_TrayPosContainer RTP on RTP.Relations_ID=TBT.Relations_ID
                        Left Outer Join TBase_Storage TBS on TBS.ContainerID=RTP.ContainerID
                        Left Outer Join TBase_Interface TBI on TBI.Sec_Mat_ID=TBS.Sec_Mat_ID
                        Left Outer Join TBase_Material TBM on TBM.Mat_Code=TBI.Mat_Code
                        Where TBP.No_Lane='" + ddlNo_Lane.SelectedValue + "' And TBP.Pos_State =1 ";
        if (txtMat_Code.Text != "")
        {
            sql = sql + " And TBM.Mat_Code like '%" + txtMat_Code.Text + "%'";
        }
        if (txtMat_Name.Text != "")
        {
            sql = sql + " And TBM.Mat_Name like '%" + txtMat_Name.Text + "%'";
        }
        
        if (txtDateS.Text != "")
        {
            sql = sql + " And TRP.CDT>='" + txtDateS.Text + "'";
        }
        if (txtDateE.Text != "")
        {
            sql = sql + " And TRP.CDT<=dateadd(d,1,convert(datetime,'" + txtDateE.Text + "'))";
        }

        try
        {
            cmd = access.GetSqlStringCommond(sql);
            ds = access.ExecuteDataSet(cmd);
            dt = ds.Tables[0];

        }
        catch
        {

        }
        return dt;
    }




    protected void btnFind_Click(object sender, ImageClickEventArgs e)
    {
        gvbind();
    }

    protected void btnReset_Click(object sender, ImageClickEventArgs e)
    {
        txtMat_Code.Text = "";
        txtMat_Name.Text = "";
       
        txtDateS.Text = "";
        txtDateE.Text = "";

        txtLineS.Text = "";
        txtColS.Text = "";
        txtLayerS.Text = "";

        txtLineE.Text = "";
        txtColE.Text = "";
        txtLayerE.Text = "";

        this.lbmsg.Text = "";


    }

    protected void btnStart_Click(object sender, ImageClickEventArgs e)
    {
        try
        {      
            txtLineS.Text = CurrentLine.Value;
            txtColS.Text = CurrentCol.Value;
            txtLayerS.Text = CurrentLayer.Value;
            Li = Convert.ToInt32(txtLineS.Text);
            Co = ddlNo_Col.SelectedValue == "1" ? Convert.ToInt32(txtColS.Text):(Convert.ToInt32(txtColS.Text) - colStart);
            La = Convert.ToInt32(txtLayerS.Text);
            if (ddlNo_Lane.SelectedValue == "1")
            {
                if (Li == 1)
                {
                    GV.Rows[La - 1].Cells[Co+1].BackColor = System.Drawing.Color.FromName("#ff0000");
                }
                else
                {
                       
                    GV.Rows[La + 3].Cells[Co+1].BackColor = System.Drawing.Color.FromName("#ff0000");

                }

            }
        }
        catch (Exception ex)
        {

        }
    }
    protected void btnEnd_Click(object sender, ImageClickEventArgs e)
    {
        txtLineE.Text = CurrentLine.Value;
        txtColE.Text = CurrentCol.Value;
        txtLayerE.Text = CurrentLayer.Value;

        Co = ddlNo_Col.SelectedValue == "1" ? Convert.ToInt32(txtColE.Text) : (Convert.ToInt32(txtColE.Text) - colStart);
        La = Convert.ToInt32(txtLayerE.Text);
        Li = int.Parse(txtLineE.Text);
        if (Li == 1)
        {
            GV.Rows[La - 1].Cells[Co + 1].BackColor = System.Drawing.Color.FromName("#ff0000");
        }
        else
        {

            GV.Rows[La + 3].Cells[Co + 1].BackColor = System.Drawing.Color.FromName("#ff0000");

        }
    }

    /// <summary>
    /// 移库操作
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnCMD_Click(object sender, ImageClickEventArgs e)
    {
        if (!ExtensionLanelists.Contains(ddlNo_Lane.SelectedValue.ToString()))  //双伸位 移库指令
        {
           ExtensionMoveCommand();
        }
        else
        {
            MoveCommand();      ////普通货位移库指令
        }
       
    }
    

    /// <summary>
    /// 普通的移库按钮操作逻辑
    /// </summary>
    private void MoveCommand()
    {
        if (txtLineS.Text == "" || txtColS.Text == "" || txtLayerS.Text == "")
        {
            lbmsg.Text = "录入的起点坐标不完整";
            return;
        }
        if (txtLineE.Text == "" || txtColE.Text == "" || txtLayerE.Text == "")
        {
            lbmsg.Text = "录入的终点坐标不完整";
            return;
        }
        lbmsg.Text = "";

        try
        {
            //int colS = ddlNo_Col.SelectedValue == "1" ? Int16.Parse(txtColS.Text) : (colStart + Int16.Parse(txtColS.Text));
            //int colE = ddlNo_Col.SelectedValue == "1" ? Int16.Parse(txtColE.Text) : (colStart + Int16.Parse(txtColE.Text));

            //调用存储过程
            cmd = access.GetStoredProcCommond("SP_GMoveByRows");
            access.AddInParameter(cmd, "@Lane", DbType.Int16, Int16.Parse(ddlNo_Lane.SelectedValue));
            access.AddInParameter(cmd, "@RowS", DbType.Int16, Int16.Parse(txtLineS.Text));
            access.AddInParameter(cmd, "@ColS", DbType.Int16, Int16.Parse(txtColS.Text));
            access.AddInParameter(cmd, "@LayerS", DbType.Int16, Int16.Parse(txtLayerS.Text));
            access.AddInParameter(cmd, "@RowE", DbType.Int16, Int16.Parse(txtLineE.Text));
            access.AddInParameter(cmd, "@ColE", DbType.Int16, Int16.Parse(txtColE.Text));
            access.AddInParameter(cmd, "@LayerE", DbType.Int16, Int16.Parse(txtLayerE.Text));
            //access.AddInParameter(cmd, "@SuanFa", DbType.Int16, Int16.Parse(rdbSuanFa.SelectedValue));
            access.AddInParameter(cmd, "@SuanFa", DbType.Int16, 0); //0 普通库点点移动
            access.AddInParameter(cmd, "@UserName", DbType.String, Request.Cookies["vNovaUserNo"].Value.ToString());
            access.AddOutParameter(cmd, "@ErrNO", DbType.Int32, -1);
            access.AddOutParameter(cmd, "@ErrMsg", DbType.String, 255);
            access.ExecuteNonQuery(cmd);
            int iResNo = Convert.ToInt32(access.GetParameter(cmd, "@ErrNO").Value.ToString());
            if (iResNo > 0)
            {
                lbmsg.Text = "指令下发成功";
                gvbind();
            }
            else
            {
                lbmsg.Text = access.GetParameter(cmd, "@ErrMsg").Value.ToString();
                return;
            }
        }
        catch (Exception ex)
        {

            throw;
        }

    }

    /// <summary>
    /// 双伸位的移库按钮逻辑
    /// </summary>
    private void ExtensionMoveCommand()
    {
        if (txtLineS.Text == "" || txtColS.Text == "" || txtLayerS.Text == "")
        {
            lbmsg.Text = "录入的起点坐标不完整";
            return;
        }
      

        lbmsg.Text = "";
        //调用双伸位移库指令生成存储过程
        cmd = access.GetStoredProcCommond("SP_GMoveByExtension_Pro");
        access.AddInParameter(cmd, "@Lane", DbType.Int16, Int16.Parse(CurrentLane.Value));
        access.AddInParameter(cmd, "@RowS", DbType.Int16, Int16.Parse(txtLineS.Text));
        access.AddInParameter(cmd, "@ColS", DbType.Int16, Int16.Parse(txtColS.Text));
        access.AddInParameter(cmd, "@LayerS", DbType.Int16, Int16.Parse(txtLayerS.Text));
        
        //access.AddInParameter(cmd, "@SuanFa", DbType.Int16, Int16.Parse(rdbSuanFa.SelectedValue));
        access.AddInParameter(cmd, "@SuanFa", DbType.Int16, 1); //1 双伸位的 自动获取终点货位
        access.AddInParameter(cmd, "@UserName", DbType.String, Request.Cookies["vNovaUserNo"].Value.ToString());
        access.AddOutParameter(cmd, "@ErrNO", DbType.Int32, -1);
        access.AddOutParameter(cmd, "@ErrMsg", DbType.String, 255);
        access.ExecuteNonQuery(cmd);
        int iResNo = Convert.ToInt32(access.GetParameter(cmd, "@ErrNO").Value.ToString());
        if (iResNo > 0)
        {
            lbmsg.Text = "指令下发成功";
            gvbind();
        }
        else
        {
            lbmsg.Text = access.GetParameter(cmd, "@ErrMsg").Value.ToString();
            return;
        }
    }

    protected void ddlNo_Col_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvbind();
    }
}